package com.bls.productmall.controller;

import com.bls.productmall.service.OrderService;
import com.bls.productmall.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.ant.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

@RestController
@RequestMapping("/api/order")
@CrossOrigin //开放前端的跨域访问
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/getOrderPage/{current}/{size}")
    public R getOrderPage(@PathVariable int current, @PathVariable int size){
        log.info("分页获取订单列表...");
        return orderService.getOrderPage(current, size);
    }

    @GetMapping("/getOrderByUserName/{userName}/{current}/{size}")
    public R getOrderByUserName( @PathVariable String userName, @PathVariable int current, @PathVariable int size){
        log.info("根据用户名来分页查询订单...");
        return orderService.getOrderByUserName(userName, current, size);
    }

    @DeleteMapping("/deleteOrderByOrderId/{orderId}")
    public R deleteOrderByOrderId(@PathVariable int orderId){
        log.info("根据订单id来删除订单...");
        int i = orderService.deleteOrderByOrderId(orderId);
        return R.ok().setMessage("成功删除" + i + "条订单");
    }

    @GetMapping("/exportExcel/{excelTitle}")
    public Object exportExcel(HttpServletResponse response, @PathVariable String excelTitle) throws IOException {
        log.info("下载订单为excel表...");
        // 创建导出文件名称 当前日期+前台传递过来的标题名（excelTitle）
        String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss") +"-"+excelTitle+".xls";
        // 设置返回的消息头和返回值类型 并设置编码 不设置编码文件名为中文的话 不会显示
        // 当设置成如下返回值时，浏览器才会执行下载文件动作
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        // 创建输出流，调用service中exportTest方法，参数：输出流 标题名
        orderService.exportExcel(response.getOutputStream(), excelTitle);
        return null;
    }

}
